'''
Description: 
Author: Zilu
Date: 2021-11-12 14:29:45
Version: 
LastEditTime: 2021-11-12 14:42:12
LastEditors: Zilu
'''

# Hmac算法：Keyed-Hashing for Message Authentication。
# 它通过一个标准算法，在计算哈希的过程中，把key混入计算过程中。
import hmac
message = b'Hello world'
key = b'secret'
h = hmac.new(key,message,digestmod='MD5')
# 消息很长，可以使用update方法
h.hexdigest()

# 将上一节的salt改为标准的hmac算法
import hashlib, random
class User(object):
    def __init__(self,username,password) -> None:
        super().__init__()
        self.username = username
        # chr 函数转换成Unicode字符
        self.key = ''.join([chr(random.randint(48, 122)) for i in range(20)])
        self.password = self.userHmac(self.key, password)

    def userHmac(self, key:str, password:str, mode = 'MD5'):
        return hmac.new(key.encode('ascii'), password.encode('ascii'), digestmod=mode)

db = {
    'michael': User('michael', '123456'),
    'bob': User('bob', 'xyz999'),
    'alice': User('alice', 'alice2008'),
    'david': User('david', '123456')
}

def login(username, password):
    return db[username].password == db[username].userHmac(db[username].key, password)

